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	0xDD, 0x5D, 0x24, 0x90, 0x56, 0x03, 0xFC, 0x8D, 0xE7, 0xC4, 0xE6, 0x1D, 0xC5, 0x8A, 0xB4, 0x8C, 0x3B, 0xA7, 0xBF, 0xE1, 0x20, 0x83, 0xC4, 0xA4, 0x09, 0x14, 0x10, 0xFE, 0x55, 0x48, 0x35, 0x99,
	0xA4, 0x6D, 0x48, 0x63, 0xFB, 0x82, 0x7C, 0x2D, 0x0C, 0xC6, 0x59, 0xB0, 0x19, 0x0D, 0x03, 0x50, 0x0D, 0x1E, 0xA7, 0x67, 0x50, 0x73, 0xA8, 0xE0, 0x54, 0xC3, 0xC0, 0x1A, 0x4E, 0x64, 0x58, 0x8E,
	0x87, 0x20, 0xC1, 0x3D, 0x2D, 0xC7, 0xF2, 0x92, 0xE2, 0xAE, 0x32, 0x60, 0xD5, 0x01, 0x9F, 0xC5, 0x22, 0xDE, 0xCE, 0x9D, 0xA2, 0x7B, 0xD8, 0xA3, 0x6A, 0x0C, 0x1E, 0x2B, 0x61, 0x0E, 0xB8, 0x1B,
	0x26, 0x84, 0x38, 0x1F, 0x77, 0xDC, 0x5B, 0x6A, 0xE8, 0x3E, 0x33, 0x10, 0x91, 0x45, 0x99, 0x5A, 0x05, 0x96, 0xB0, 0xD5, 0xF6, 0x9E, 0x84, 0xDF, 0x9B, 0x51, 0x74, 0xE5, 0x37, 0x11, 0x42, 0x05,
	0xBA, 0x23, 0x5C, 0x49, 0x96, 0x9A, 0x1C, 0x98, 0x4F, 0xCE, 0x60, 0xD4, 0x27, 0x61, 0x81, 0x4C, 0x31, 0x43, 0xFE, 0xBB, 0x66, 0x13, 0x16, 0x72, 0x7A, 0xA0, 0x7B, 0xC1, 0xB9, 0x5E, 0xCA, 0x32,
};

void MMdec::dec(const string& _FileName)
{
	string _FileNameN = _FileName;
	string kBuff;
	if (RWFile::LoadFile(_FileNameN, kBuff))
	{
		int len = kBuff.length();
		BYTE* data = (BYTE*)kBuff.c_str();
		MMdec kMMdec;
		kMMdec.SetKeyEx(0xFA);
		kMMdec.DoDecode(0x7B, len, data, data);
		RWFile::SaveFile(_FileNameN + ".txt", kBuff);
	}
}

MMdec::MMdec()
{
	kKeyData = CryptTbl;
	m_byKeyEx = 0;
}

void MMdec::SetKeyEx(BYTE byKeyEx)
{
	m_byKeyEx = byKeyEx;
}

void MMdec::DoDecode(BYTE key, int len, BYTE *Dst, BYTE *Src)
{
	BYTE Key1 = kKeyData[(BYTE)(2 * key + 1)];
	BYTE Key2 = kKeyData[2 * m_byKeyEx];
	int iIdx = 0;
	if (len > 0)
	{
		do
		{
			Dst[iIdx] = Src[iIdx] ^ Key1 ^ Key2 ^ kKeyData[511 - (2 * iIdx) % 512];
			++iIdx;
		} while (iIdx < len);
	}
}
